<?php
namespace app\index\validate;
use think\Validate;
use think\Db;
//租客接口验证类
class Tenant extends Validate{
	public $house;
	protected $rule = [
    	'house_id'		=> ['require','check_house'],
    	'month'			=> ['require','in:1,2,3,4,5,6,7,8,9,10,11,12'],
    	'day'			=> ['require','between:1,31'],
    	'hour'			=> ['require','in:9,10,11,12,14,15,16,17'],
    	'minute'		=> ['require','in:0,30'],
    	'phone'			=> ['require','checkphone'],
    	'smscode'		=> ['require','checkSmscode:sms'],
    ];
    protected $message=[
		'house_id.require'		=>'房源主键不能为空',
		'house_id.check_house'	=>'房源主键无效',
		'month.require'			=>'预约看房月份不能为空',
		'month.in'				=>'月份格式错误',
		'day.require'			=>'预约看房日期不能为空',
		'day.between'			=>'日期格式错误',
		'hour.require'			=>'预约看房小时不能为空',
		'hour.in'				=>'小时范围错误错误',
		'minute.require'		=>'预约看房分钟不能为空',
		'minute.in'				=>'分钟范围错误错误',
		'contract_id.require'   =>'合同主键不能为空',
		'phone.require'	    => '手机号码不能为空',
		'phone.checkphone'  => '手机号码格式错误',
		'smscode.require'		=> '手机验证码不能为空',
		'smscode.checkSmscode'	=> '验证码错误或已过期',
	];
	protected $scene=[
		'see_house_stat'=>['house_id','month','day'],
		'see_house'=>[
			'house_id',
			'month',
			'day',
			'hour',
			'minute'
		],
		'retreat_house'=>[
			'contract_id'
		],
		'apply_ower'=>[
			'phone'	 =>'require|checkphone',
			'smscode'=>'require|checkSmscode:sms'
		],
	];
	//验证手机号
	protected function checkphone($val){
		return check_mobile($val);
	}
	//验证验证码
	protected function checkSmscode($key,$rule,$data){
		$smsLog = Db::name('smsLog')->where(['phone' => $data['phone'], 'stat' => 1])->order('id desc')->find();
		if(!$smsLog){
			return false;
		}elseif($smsLog['smscode'] != $data['smscode']){
			return false;
		}elseif($smsLog['exp_time'] < time()){
			Db::name('smsLog')->where('id',$smsLog['id'])->update(['stat' => 2]);
			return false;
		}else{
			Db::name('smsLog')->where('id',$smsLog['id'])->update(['stat' => 2]);
			return true;
		}
	}
	//检测房源主键
	protected function check_house($house_id){
		$house=Db::name('house')->where('id',$house_id)->find();
		if(!$house || $house['stat']!=1 || $house['del']!=0){
			return false;
		}else{
			$this->house=$house;
			return true;
		}
	}
}